import React, { useEffect, useState } from "react";
import DateTimeRange from "../../DateTimeRange";
import { Timestamp } from "../type";

interface Props {
  timeMark?: string | undefined;
  handleConfirm: (v: string, timestamp: Timestamp) => void;
}

function AbsoluteTime({ handleConfirm, timeMark }: Props) {
  const [timeRangeValue, setTimeRangeValue] = useState<string | null>(null);
  useEffect(() => {
    setTimeRangeValue(timeMark ?? null);
  }, []);
  const handleOnChange = (value: [number | null, number | null] | null) => {
    if (!value) {
      setTimeRangeValue(null);
      return;
    }
    const [start, end] = value ?? [];
    if (!start || !end) {
      return;
    }
    setTimeRangeValue(`${start}/${end}`);
    handleConfirm(`${start}/${end}`, { start, end });
  };
  if (timeRangeValue && timeRangeValue?.indexOf("/") > -1) {
    const [start, end] = timeRangeValue.split("/");
    return (
      <DateTimeRange
        onChange={handleOnChange}
        value={[Number(start), Number(end)]}
        label=""
        getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
      />
    );
  }
  return (
    <DateTimeRange
      onChange={handleOnChange}
      label=""
      value={null}
      getPopupContainer={(triggerNode: any) => triggerNode.parentNode}
    />
  );
}

export default AbsoluteTime;
